package com.tpshion.cloud.oss.interceptor;

import com.tpshion.cloud.common.support.CoreException;
import com.tpshion.cloud.common.support.ErrorCode;
import com.tpshion.cloud.common.support.Field;
import com.tpshion.cloud.common.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截处理
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行options请求类型
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            return true;
        }

        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        log.info("登录验证处理 [{}]  {}",request.getMethod(),request.getServletPath());
        //验证token
        String token = request.getHeader(Field.TOKEN);
        if(StringUtils.isEmpty(token)){
            log.info("*** path:{} no access...",request.getServletPath());
            throw new CoreException(ErrorCode.NO_LOGIN);
        }
        try {
            JwtUtil.checkToken(token);
        }catch (CoreException e){
            throw new CoreException(ErrorCode.LOGIN_TIMEOUT);
        }
        log.info("*** path:{} allow access...",request.getServletPath());
        return true;
    }
}
